package Controller;

import Dto.UserTbEntity;
import MEx.MExAPI;
import repository.LoginRepositor;
import repository.UserRepository;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by MonsterENT on 10/10/17.
 */
@WebServlet(name = "LoginController")
public class LoginController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
//        System.out.println("Account="+request.getParameter("userAccount"));
//        System.out.println("Password="+request.getParameter("userPwd"));

        if(request.getParameter("FN").equals("0"))
        {
            return;
        }
        PrintWriter out = response.getWriter();
        try {
            //进入repository层 判断登陆用户是否存在
            LoginRepositor repos = new LoginRepositor();
//            boolean resssss = true;
//            resssss = repos.login(request.getParameter("userAccount"),request.getParameter("userPwd"));
//            System.out.println("resssss="+resssss);
            if(repos.login(request.getParameter("userAccount"),request.getParameter("userPwd"))) {
                //进入repository层 获取用户信息
                UserRepository userRepository = new UserRepository();
                //get,set
                UserTbEntity userModel = new UserTbEntity();
                userRepository.getUserInfoByAccount(request.getParameter("userAccount"),userModel);
                System.out.println("name"+userModel.getUserName());
                System.out.println("admin="+userModel.getAdmin());

                //信息组装
                String JsonStr = "{ \"UserInfo\":";

                String[] Keys = {"userName","userAccount","userID","userType","userStatus","admin"};
                Object[] objs = {userModel.getUserName(),userModel.getUserAccount(),userModel.getUserId(),userModel.getUserType(), userModel.getUserStatus(),userModel.getAdmin()};

                JsonStr += MExAPI.toJson(Keys,objs);
                JsonStr += ",";
                out.write(JsonStr + "\"Result\":\"Success\"}");
            }
            else
                out.write("{\"Result\":\"Fail\"}");
        }
        catch (Exception e){
            out.write("{\"Result\":\"Fail\"}");
        }
        finally{
            out.flush();
            out.close();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
